﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core.Models;
using BootstrapAdmin.Web.Core.Services;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services;

internal sealed class AlarmService : IAlarmService
{
    private readonly IDBManager _dbManager;

    public AlarmService(IDBManager db) => _dbManager = db;

    public async Task<ApiResult> SaveAlarmsAsync(ApiData data)
    {
        if (data.Values.Length == 0)
        {
            return ApiResult.Ok();
        }

        var alarmValues = data.Values[0].GetValue<bool[]>(); // 警报数据（JSON 转换后成了 bool 类型）
        try
        {
            using var db = _dbManager.Create();

            // 按位解析
            var sql = new Sql();
            sql.Where("Category = @0", "Alarm");
            var alarmDicts = await db.FetchAsync<DictInfo>(sql);

            // 根据字典表中的配置，解析 int32 对应位（从低到高位）警报类型。
            // 字典配置基数从 1 开始。
            var alarmRecords = new List<AlarmRecord>();
            for (int i = 0; i < alarmValues!.Length; i++)
            {
                if (alarmValues[i])
                {
                    var alarmDict = alarmDicts.FirstOrDefault(s => s.Code == (i + 1).ToString());
                    if (alarmDict != null)
                    {
                        var alarm = new AlarmRecord
                        {
                            Station = data.Schema.Station,
                            Classify = alarmDict.Name,
                            Desc = alarmDict.Alias,
                            CreatedAt = DateTime.Now,
                        };
                        alarmRecords.Add(alarm);
                    }
                }
            }

            db.InsertBatch(alarmRecords);
        }
        catch (Exception ex)
        {
            return ApiResult.Error(ex.Message);
        }

        return ApiResult.Ok();
    }
}
